package com.maddox.relax.dialog;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatSpinner;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.maddox.relax.R;
import com.maddox.relax.adapter.PhotoPickerAdapter;
import com.maddox.relax.listener.OnImageTakeCompleteListener;
import com.maddox.relax.model.ImageInfo;
import com.maddox.relax.model.ImageSet;
import com.maddox.relax.util.LogUtil;
import com.maddox.relax.util.PBitmapUtils;
import com.maddox.relax.view.MRecyclerViewItemDecoration;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class PhotoPickerDialog extends AlertDialog implements AdapterView.OnItemSelectedListener {

    private ImageView pickerBack;
    private AppCompatSpinner pickerSpinner;
    private TextView tvConfirm, pickerTitle;
    private RecyclerView pickerRecycler;
    private PhotoPickerAdapter photoPickerAdapter;
    private Context mContext;


    private List<ImageInfo> allMedias;
    private List<ImageInfo> onlyImages;
    private List<ImageInfo> onlyVideos;
    private OnImageTakeCompleteListener completeListener;
    //是否开启压缩
    private boolean isCompress = true;


    public PhotoPickerDialog(@NonNull Context context) {
        super(context, R.style.PhotoPickerDialog);
        this.mContext = context;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_image_picker);
        setCancelable(false);
        initView();
    }

    private void initView() {
        pickerBack = findViewById(R.id.picker_close);
        pickerSpinner = findViewById(R.id.picker_spinner);
        tvConfirm = findViewById(R.id.picker_confirm);
        pickerTitle = findViewById(R.id.picker_title);
        pickerRecycler = findViewById(R.id.picker_recycler);
        pickerBack.setOnClickListener(v -> dismiss());
        tvConfirm.setOnClickListener(v -> completePick());
        pickerRecycler.setLayoutManager(new StaggeredGridLayoutManager(4, GridLayoutManager.VERTICAL));
        pickerRecycler.setItemAnimator(new DefaultItemAnimator());
        pickerRecycler.addItemDecoration(new MRecyclerViewItemDecoration(2));
//        pickerRecycler.addItemDecoration(new DividerItemDecoration(mContext,DividerItemDecoration.VERTICAL));
        photoPickerAdapter = new PhotoPickerAdapter(mContext, null);
        pickerRecycler.setAdapter(photoPickerAdapter);
        LogUtil.d("照片选择框初始化完成");
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(mContext, android.R.layout.simple_list_item_1, new String[]{"图片视频", "仅有图片", "仅有视频"});
        pickerSpinner.setAdapter(arrayAdapter);

    }

    private LoadindDialog loadindDialog = null;

    private void completePick() {
        if (photoPickerAdapter.getSelectSize() <= 0) {
            dismiss();
            Toast.makeText(mContext, "未选择任何内容", Toast.LENGTH_SHORT).show();
            return;
        }
        loadindDialog = new LoadindDialog(mContext, "正在处理...");
        loadindDialog.show();
        if (isCompress) {
            //获取所有的选择图片信息,进入压缩线程
            List<File> selectFiels = photoPickerAdapter.getSelectFiles();
            String imageDir = PBitmapUtils.getPickerFileDirectory(mContext).getAbsolutePath();
            ArrayList<ImageInfo> resultList = new ArrayList<>();

            Luban.with(mContext)
                    .load(selectFiels)
                    .ignoreBy(200)
                    .setTargetDir(imageDir)
                    .setRenameListener(path -> {
                        String substring = path.substring(path.lastIndexOf("/"));
                        String replace = substring.replace("IMG_", "IMG_CP_");
                        return replace;
                    })
                    .setCompressListener(new OnCompressListener() {
                        @Override
                        public void onStart() {

                        }

                        @Override
                        public void onSuccess(File file) {
                            //处理图片,并进行压缩
                            ImageInfo imageInfo = new ImageInfo();
                            imageInfo.filePath = file.getAbsolutePath();
                            imageInfo.fileName = file.getName();
                            int[] size = PBitmapUtils.getImageWidthHeight(file.getAbsolutePath());
                            imageInfo.width = size[0];
                            imageInfo.height = size[1];
                            resultList.add(imageInfo);
                            LogUtil.d("压缩后-->" + imageInfo.filePath);
                            if (resultList.size() == selectFiels.size()) {
                                LogUtil.d("全部压缩完成,回调出去");
                                dismiss();
                                loadindDialog.dismiss();
                                if (completeListener != null) {
                                    completeListener.onImageTakeComplete(resultList);
                                }

                            }
                        }

                        @Override
                        public void onError(Throwable e) {
                            LogUtil.d("选取相册图片压缩失败:" + e + "--->转为原图返回");
                            isCompress = false;
                            completePick();
                        }
                    })
                    .launch();


        } else {
            //原图地址返回
            ArrayList<ImageInfo> selectDatas = photoPickerAdapter.getSelectDatas();
            dismiss();
            loadindDialog.dismiss();
            if (completeListener != null) {
                completeListener.onImageTakeComplete(selectDatas);
            }

        }

    }

    public void setIsMultiple(boolean isMultiple) {
        photoPickerAdapter.setMultiple(isMultiple);
    }

    public void setData(List<ImageInfo> imageInfos) {
        allMedias = imageInfos;
        photoPickerAdapter.addData(imageInfos);
        branchAllImages(allMedias);
        pickerSpinner.setOnItemSelectedListener(this);
    }

    private void branchAllImages(List<ImageInfo> allImages) {
        onlyImages = new ArrayList<>();
        onlyVideos = new ArrayList<>();
        for (ImageInfo item : allImages) {
            if (item.isVideo()) {
                onlyVideos.add(item);
            } else {
                onlyImages.add(item);
            }
        }
    }


    public void setMediaType(int mediaType) {
        switch (mediaType) {
            case ImageSet.TYPE_ALL_MEDIA:
                pickerSpinner.setVisibility(View.VISIBLE);
                pickerTitle.setVisibility(View.INVISIBLE);
                //含有视频的情况下取消压缩
                isCompress = false;
                break;
            case ImageSet.TYPE_ALL_IMAGE:
                pickerSpinner.setVisibility(View.INVISIBLE);
                pickerTitle.setVisibility(View.VISIBLE);
                break;
            case ImageSet.TYPE_ALL_VIDEO:
                pickerSpinner.setVisibility(View.INVISIBLE);
                pickerTitle.setVisibility(View.VISIBLE);
                //含有视频的情况下取消压缩
                isCompress = false;
                break;

        }

    }

    private boolean inFirstTime = true;

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

        if (inFirstTime) {
            inFirstTime = false;
            return;
        }
        LogUtil.d("选择类型_______________>");
        switch (position) {
            case 0:
                photoPickerAdapter.addDataNew(allMedias);
                break;

            case 1:
                photoPickerAdapter.addDataNew(onlyImages);
                break;

            case 2:
                photoPickerAdapter.addDataNew(onlyVideos);
                break;
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }


    public void setOnImagesConfirmListener(OnImageTakeCompleteListener completeListener) {

        this.completeListener = completeListener;
    }
}
